package copyengine.dataLayer.query.local
{
	import copyengine.dataLayer.query.database.CEDatabaseQueryManger;

	public class CELocalQueryWarp
	{
		private var uniqueKey:String;

		private var callBackFunctionVector:Vector.<Function>;

		private var databaseQueryArray:Array;

		private var resultData:Object;

		private var remainCount:int;

		private var isDuringExecute:Boolean;

		private var manger:CELocalQueryExcuteManger;

		public function CELocalQueryWarp(_uniqueKey:String, _databaseQueryArray:Array, _manger:CELocalQueryExcuteManger)
		{
			isDuringExecute = false;
			databaseQueryArray = _databaseQueryArray;
			remainCount = _databaseQueryArray.length;
			resultData = {};
			uniqueKey = _uniqueKey;
			callBackFunctionVector = new Vector.<Function>();
			manger = _manger;
		}

		public function execute():void
		{
			if (!isDuringExecute)
			{
				for (var i:int = 0; i < databaseQueryArray.length; i++)
				{
					CEDatabaseQueryManger.instance.excuteDatabaseQuery(onDatabaseQueryFinished, databaseQueryArray[i][0], databaseQueryArray[i][1]);
				}
			}
			isDuringExecute = true;
		}

		public function addCallbackFunction(_f:Function):void
		{
			callBackFunctionVector.push(_f);
		}

		public function removeCallBackFunction(_f:Function):Boolean
		{
			for (var i:int = 0; i < callBackFunctionVector.length; i++)
			{
				if (callBackFunctionVector[i] == _f)
				{
					callBackFunctionVector.splice(i, 1);
					return true;
				}
			}
			return false;
		}

		public function getUniqueKey():String
		{
			return uniqueKey;
		}

		private function onDatabaseQueryFinished(_queryName:String, _param:Object):void
		{
			resultData[_queryName] = _param;
			remainCount--;
			tryToFinisehd();
		}

		private function tryToFinisehd():void
		{
			if (remainCount <= 0)
			{
				while (callBackFunctionVector.length > 0)
				{
					var callBackFunction:Function = callBackFunctionVector.pop();
					callBackFunction(resultData);
				}
				manger.removeLocalQuery(this);
			}
		}

		private function dispose():void
		{
			uniqueKey = null;
			callBackFunctionVector = null;
			databaseQueryArray = null;
			resultData = null;
		}

	}
}
